import { store } from "../../../store/index";
import { editUserInfo, uploadFile } from "../../api/index";

Page({
  data: {
    userInfo: {},
    file_id: ''
  },

  onLoad() {
    this.setData({
      userInfo: {
        name: store.userInfo.name || '',
        sex: store.userInfo.sex || '',
        prefer: store.userInfo.prefer || '',
        sign: store.userInfo.sign || '',
        img: store.userInfo.img || '',
        inviter: store.userInfo.inviter || ''
      },
    });
  },
  editAvatar() {
    console.log('editAvatar');
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 先显示选中的图片
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            img: tempFilePath
          }
        });
        // 上传图片
        uploadFile({
          file: tempFilePath
        }).then(res => {
          this.setData({
            file_id: res
          });
        });
      }
    });
  },
  
  onChange(event) {
    const key = event.currentTarget.dataset.key;
    if (key === 'sex') {
      this.setData({
        [`userInfo.${key}`]: event.detail
      });
    } else {
      this.setData({
        [`userInfo.${key}`]: event.detail.value
      });
    }
  },

  onSave() {
    if (!this.data.userInfo.inviter) {
      wx.showToast({
        icon: 'none',
        title: '邀请人必填'
      })
      return
    }
    // 保存修改逻辑
    console.log('保存成功');
    editUserInfo({
      ...this.data.userInfo,
      img: this.data.file_id || this.data.userInfo.img
    }).then(res => {
      console.log(res);
      if (res.code === 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        });
      }
      store.getUserInfo();
      wx.navigateBack();
    });
  }
});
